import { axios } from "../../request";
import regeneratorRuntime from "../../libs/runtime";
// pages/goods_detail/index.js
Page({
    // 用一个对象管理加入购物车的商品数据
  goods_OBJ:{},
  /**
   * 页面的初始数据
   */
  data: {
    pics: [],
    goods_introduce: "",
    goods_name:'',
    goods_price:0,
    goods_id:0
  },
  // 获取商品详情资料
  async getGoodsDetail() {
    const data = {
      // 接受路由传参的id
      goods_id: this.options.id
    };
    const res = await axios({ url: "/goods/detail", data });
    let { pics, goods_introduce,goods_name,goods_price,goods_id,goods_small_logo  } = res.message;
    console.log('res.message: ', res.message);
    const res2 = await this.initWebpIOS(goods_introduce);
    goods_introduce = res2;
    this.setData({ pics, goods_introduce,goods_name,goods_price,goods_id});
    this.goods_OBJ = { goods_name,goods_price,goods_id,goods_small_logo,number:1,isSelect:false    }
  },
  // 处理IOS不兼容webp
  initWebpIOS(str) {
    // 获取系统信息
    // https://developers.weixin.qq.com/miniprogram/dev/api/base/system/system-info/wx.getSystemInfo.html
    return wx.getSystemInfo().then(res => {
      // 将字符串转成小写
      let system = res.system.toLowerCase();
      system = system.indexOf("ios");
      if (system > -1) {
        // console.log('ios');
        str = str.replace(/\?.+?webp/g, "");
      }
      return str;
    });
  },
  // 加入购物车
  addCart(){
   const cartArr = wx.getStorageSync('cart') || [];
   const cartIndex =  cartArr.findIndex(item=>{
     return item.goods_id == this.goods_OBJ.goods_id
    })
    if (cartIndex > -1 ) {
      cartArr[cartIndex].number++
      console.log('cartArr[cartIndex].number: ', cartArr[cartIndex].number);
    }else{
      cartArr.push(
        this.goods_OBJ
        )
      }
      wx.showToast({
        title:'加入购物车成功',
        // 显示透明蒙层，防止触摸穿透
        mask:true
      })
       wx.setStorageSync('cart',cartArr );
          
        
// console.log('加入购物车2');
  },
  // 前往购物车页面
  goToCart(){
    wx.switchTab({
      url: '/pages/cart/index'
    });
      
  },
  onShow: function() {
    this.getGoodsDetail();
  }
});
